const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql2');
const bcrypt = require('bcryptjs');
const nodemailer = require('nodemailer');
const cors = require('cors');

const app = express();
const PORT = 8083;

// MySQL 连接配置
const db = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'flask_sql'
});

// 连接到数据库
db.connect((err) => {
    if (err) {
        throw err;
    }
    console.log('MySQL connected...');
});

// 中间件
app.use(cors());
app.use(bodyParser.json());

// 创建邮件发送器
const transporter = nodemailer.createTransport({
    service: 'qq',
    auth: {
        user: '1620886575@qq.com',
        pass: 'clxrnzqmgcobfacj'
    }
});

// 生成验证码函数
const generateVerificationCode = () => {
    return Math.floor(100000 + Math.random() * 900000).toString(); // 生成6位随机数
};

// 发送验证码邮件
const sendVerificationEmail = (email, code) => {
    const mailOptions = {
        from: '1620886575@qq.com',
        to: email,
        subject: '验证码',
        text: `您的验证码是：${code}`
    };

    transporter.sendMail(mailOptions, (err, info) => {
        if (err) {
            console.log('发送邮件失败:', err);
        } else {
            console.log('邮件发送成功:', info.response);
        }
    });
};

// 注册路由
app.post('/register', async (req, res) => {
    try {
        const { username, password, email, role } = req.body;

        // 检查用户名是否已存在
        db.query('SELECT username FROM users WHERE username = ?', [username], async (err, result) => {
            if (err) throw err;
            if (result.length > 0) {
                return res.status(400).send({ message: '用户名已存在' });
            }

            // 密码加密
            const hashedPassword = await bcrypt.hash(password, 10);

            // 生成验证码并发送邮件
            const verificationCode = generateVerificationCode();
            sendVerificationEmail(email, verificationCode);

            // 插入新用户数据
            const newUser = { username, password: hashedPassword, email, role, verification_code: verificationCode };
            db.query('INSERT INTO users SET ?', newUser, (err, result) => {
                if (err) throw err;
                res.status(201).send({ message: '注册成功！请检查您的电子邮件以获取验证码。' });
            });
        });
    } catch (error) {
        res.status(500).send({ message: '注册失败', error });
    }
});

// 发送验证码路由
app.post('/send-verification-code', (req, res) => {
    const { email } = req.body;
    const verificationCode = generateVerificationCode();
    sendVerificationEmail(email, verificationCode);
    res.status(200).send({ message: '验证码已发送', verificationCode });
});

// 登录路由
app.post('/login', (req, res) => {
    const { username, password, verificationCode } = req.body;

    // 查询用户
    db.query('SELECT * FROM users WHERE username = ?', [username], async (err, result) => {
        if (err) throw err;
        if (result.length === 0) {
            return res.status(400).send({ message: '用户名不存在' });
        }

        const user = result[0];

        // 检查密码
        const isMatch = await bcrypt.compare(password, user.password);
        if (!isMatch) {
            return res.status(400).send({ message: '密码错误' });
        }

        // 登录成功
        res.status(200).send({ message: '登录成功', user: { username: user.username, role: user.role } });
    });
});

// 处理用户信息录入的路由
app.post('/add-user', (req, res) => {
    const { name, age, idCard, photoUrl } = req.body;

    // 插入新用户详细信息
    const newUserDetails = { name, age, idCard, photoUrl };
    db.query('INSERT INTO staff SET ?', newUserDetails, (err, result) => {
        if (err) throw err;
        res.status(201).send({ message: '用户信息录入成功！' });
    });
});

// 获取所有用户信息
app.get('/users', (req, res) => {
    db.query('SELECT * FROM staff', (err, results) => {
        if (err) {
            return res.status(500).send({ message: '获取用户信息失败', error: err });
        }
        res.status(200).send(results);
    });
});

// 获取指定ID的用户信息
app.get('/users/:id', (req, res) => {
    const userId = req.params.id;
    db.query('SELECT * FROM staff WHERE id = ?', [userId], (err, result) => {
        if (err) {
            return res.status(500).send({ message: '获取用户信息失败', error: err });
        }
        if (result.length === 0) {
            return res.status(404).send({ message: '用户不存在' });
        }
        res.status(200).send(result[0]);
    });
});

// 更新指定ID的用户信息
// 更新指定ID的用户信息
app.put('/users/:id', (req, res) => {
    const userId = req.params.id;
    const { name, age, idCard, photoUrl } = req.body;
    const updatedUserDetails = { name, age, idCard, photoUrl };
    db.query('UPDATE staff SET ? WHERE id = ?', [updatedUserDetails, userId], (err, results) => {
        if (err) {
            return res.status(500).send({ message: '更新用户信息失败', error: err });
        }
        res.status(200).send({ message: '用户信息更新成功' });
    });
});


// 删除指定ID的用户
    app.delete('/users/:id', (req, res) => {
        const userId = req.params.id;
        db.query('DELETE FROM staff WHERE id = ?', [userId], (err, results) => {
            if (err) {
                return res.status(500).send({ message: '删除用户失败', error: err });
            }
            res.status(200).send({ message: '用户删除成功' });
        });
    });

// 获取所有危险行为
    app.get('/api/dangerous-behaviors', (req, res) => {

        db.query('SELECT * FROM dan', (err, results) => {
            if (err) {
                return res.status(500).send({ message: '获取危险行为失败', error: err });
            }
            res.status(200).send(results);
        });
    });

// 获取所有危险人物
    app.get('/api/dangerous-persons', (req, res) => {
        db.query('SELECT * FROM dangerous_persons', (err, results) => {
            if (err) {
                return res.status(500).send({ message: '获取危险人物失败', error: err });
            }
            res.status(200).send(results);
        });
    });

// 删除指定ID的危险行为
    app.delete('/api/dangerous-behaviors/:id', (req, res) => {
        const behaviorId = req.params.id;
        db.query('DELETE FROM dan WHERE id = ?', [behaviorId], (err, results) => {
            if (err) {
                return res.status(500).send({ message: '删除危险行为失败', error: err });
            }
            res.status(200).send({ message: '危险行为删除成功' });
        });
    });

// 删除指定ID的危险人员
    app.delete('/api/dangerous-persons/:id', (req, res) => {
        const personId = req.params.id;
        db.query('DELETE FROM dangerous_persons WHERE id = ?', [personId], (err, results) => {
            if (err) {
                return res.status(500).send({ message: '删除危险人员失败', error: err });
            }
            res.status(200).send({ message: '危险人员删除成功' });
        });
    });

// 启动服务器
    app.listen(PORT, () => {
        console.log(`Server is running on http://localhost:${PORT}`);
    });
